<template>
	<view>
		<view v-for="(item,index) in indexList" :key="index">
			<view>{{item.title}}</view>
			<view v-for="(datas,index) in item.datas" :key="index">
				{{datas.name.name}}
			</view>
		</view>
	</view>
</template>

<script>
	import Pinyin from '@/static/pinyin.js';
	export default {
		data() {
			return {
				indexList: [] //列表
			};
		},
		created() {
			var ind = [{// 模拟数据
					"id": 1,
					"name": "万景千言"
				},
				{
					"id": 2,
					"name": "八里沟11"
				},
				{
					"id": 2,
					"name": "八里沟1"
				},
				{
					"id": 2,
					"name": "八里沟"
				},
				{
					"id": 17,
					"name": "京华园"
				},
				{
					"id": 21,
					"name": "平原博物馆"
				},
				{
					"id": 38,
					"name": "金牛湖野生动物王国"
				}
			]
			this.pinyinSort(ind);
		},
		methods: {
			pinyinSort(name) {
				var pinyinArray = new Array();
				for (var bukn = 0; bukn < name.length; bukn++) {
					var o = new Object();
					var ken = Pinyin.getSpell(name[bukn].name, function(charactor, spell) {
						return spell[1];
					});
					o.name = name[bukn];
					o.pinyin = ken.split(',').join('');
					pinyinArray.push(o);
				}
				let map = {
					title: '',
					datas: []
				};
				pinyinArray.forEach((item, index) => {
					if (!map[item.pinyin[0].toUpperCase()]) {
						map[item.pinyin[0].toUpperCase()] = {
							title: item.pinyin[0].toUpperCase(),
							datas: []
						};
					}
					map[item.pinyin[0].toUpperCase()].datas.push({
						name: item.name,
						pinyin: item.pinyin
					});
				});
				var turn = new Array();
				var letters = '*ABCDEFGHIJKLNMOPQRSTUVWXYZ'.split('');
				for (var i = 1; i < letters.length; i++) {
					if (map[letters[i]]) {
						var obj = new Object();
						obj.title = letters[i];
						obj.datas = map[letters[i]].datas;
						turn.push(obj);
					}
				}
				//对景区名称进行排序
				let arr = turn;
				var compare = function(obj1, obj2) {
					var val1 = obj1.pinyin;
					var val2 = obj2.pinyin;
					if (val1 < val2) {
						return -1;
					} else if (val1 > val2) {
						return 1;
					} else {
						return 0;
					}
				};
				for (let i = 0; i < arr.length; i++) {
					arr[i].datas.sort(compare);
				}
				this.indexList = arr;
			}
		}
	};
</script>

<style>

</style>
